package com.spancer.contentcenter.configuration;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * author by: mars
 * Date: 2020/8/17 16:37
 * Description: nacos-ribbon支持权重，自定义权重
 */
@Slf4j
public class NacosWeightedRule extends AbstractLoadBalancerRule {
    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
        // 读取配置文件
    }

    @Override
    public Server choose(Object key) {
        // 获取ribbon入口
        BaseLoadBalancer lb = (BaseLoadBalancer)this.getLoadBalancer();
        log.info("lb={}",lb);
        // 获取微服务名称
        String name = lb.getName();
        // 获取服务发现的相关Api
        NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
        try {
            // 实现负载均衡算法，使用nacos-client的权重算法,获取实例
           Instance instance =  namingService.selectOneHealthyInstance(name);
           // 将Instance 转换为 Server ==> new NacosServer(instance)
            log.info("choosed instance port={},instanceIp={}",instance.getPort(),instance.getIp());
           return new NacosServer(instance);
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return null;
    }
}
